import api from './index'

interface InitKeysResponse {
  identityKey: {
    id: number;
    publicKey: string;
    cipher: string;
    salt: string;
    timestamp: string;
  };
  signedPreKey: {
    id: number;
    publicKey: string;
    signature: string;
    cipher: string;
    salt: string;
    timestamp: string;
  };
  preKeys: Array<{
    id: number;
    publicKey: string;
    cipher: string;
    salt: string;
  }>;
  passwordHash: string;
  passwordSalt: string;
  oneTimeId: string;
  localId: number;
}

// 初始化密钥包
export function initSecureKeys(userId: string, password: string) {
  return api.post<InitKeysResponse>('/secure/init', { userId, password }).then(async (keys) => {
    if (!keys) {
      throw new Error('无效的密钥包响应数据');
    }

    await storeInitKeys(userId, keys);
    return keys;
  });
}

export async function storeInitKeys(userId: string, keys: any) {
  if (
    !keys ||
    !keys.identityKey ||
    !keys.signedPreKey ||
    !Array.isArray(keys.preKeys)
  ) {
    throw new Error('无效的密钥包数据');
  }

  const payload = {
    userId : userId,
    identityKey: {
      id: keys.identityKey.id,
      publicKey: keys.identityKey.publicKey,
      user: keys.localId.toString(),
      cipher: keys.identityKey.cipher,
      salt: keys.identityKey.salt,
      active: true,
      timestamp: keys.identityKey.timestamp,
    },
    signedPreKey: {
      id: keys.signedPreKey.id,
      publicKey: keys.signedPreKey.publicKey,
      signature: keys.signedPreKey.signature,
      user: keys.localId.toString(),
      cipher: keys.signedPreKey.cipher,
      salt: keys.signedPreKey.salt,
      active: true,
      timestamp: keys.signedPreKey.timestamp,
    },
    preKeys: keys.preKeys.map((preKey) => ({
      id: preKey.id,
      publicKey: preKey.publicKey,
      user: keys.localId.toString(),
      used: false,
      cipher: preKey.cipher,
      salt: preKey.salt,
    })),
    passwordHash: keys.passwordHash,
    passwordSalt: keys.passwordSalt,
    oneTimeId: keys.oneTimeId,
    localId: keys.localId,
  };

  return api.post('/keys/storeInitKey', payload);
}

// 获取密钥包信息
export function getSecureKeys() {
  return api.get<{ code: number; message: string; data: any; timestamp: number }>('/keys/fetchInitKeys')
    .then(response => response.data);
} 